//
//  YWLoginViewController.m
//  maintain
//
//  Created by 郑想 on 15/10/19.
//  Copyright © 2015年 ewin. All rights reserved.
//

#import "MBProgressHUD.h"

#import "Masonry.h"

#import "UIButton+Animations.h"
#import "UIColor+CustomColors.h"
#import "UIView+Extension.h"
#import "UIViewController+MJPopupViewController.h"
#import "UIWindow+Extension.h"
#import "WMHttpTool.h"

#import "YWCommonTool.h"
#import "YWConst.h"
#import "YWDBTool.h"
#import "YWDownloadMetaDataManager.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWLoginViewController.h"
#import "YWMacro.h"
#import "YWMissionManager.h"
#import "YWOrganization.h"
#import "YWPopupOrganizationViewController.h"
#import "YWPushManager.h"
#import "YWResourceManager.h"
#import "YWEwinManager.h"

#define kLoginLalelFont [UIFont systemFontOfSize:16]
#define kLoginTextFieldFont [UIFont systemFontOfSize:16]

@interface YWLoginViewController () <UITextFieldDelegate, YWPopupSelectOrganizationDelegate> {
    //键盘弹出移动前的bgView的Y值
    CGFloat originalBgViewY;
}

@property (nonatomic, strong) UIView* bgView;
@property (nonatomic, strong) UIImageView* bgImageView;

@property (nonatomic, strong) UIImageView* logoImageView;

@property (nonatomic, strong) UILabel* userAccountLabel;
@property (nonatomic, strong) UILabel* pwdAccountLabel;

@property (nonatomic, strong) UITextField* userAccountTextField;
@property (nonatomic, strong) UITextField* pwdTextField;

@property (nonatomic, strong) UIButton* loginBtn;

@property (nonatomic, strong) YWPopupOrganizationViewController* popupOrganizationViewController;
@property (nonatomic, strong) MBProgressHUD* HUD;
@end

@implementation YWLoginViewController
#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor customBackgroudColor];
    
    [self autoLayoutView];
    //[self registerForKeyboardNotifications];
    originalBgViewY = self.bgView.y;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Init methods
- (UIView*)bgView
{
    if (!_bgView) {
        CGFloat bgViewH = 270;
        UIView* bgView = [[UIView alloc] initWithFrame:CGRectMake(0, (SCREEN_HEIGHT - bgViewH) / 3, SCREEN_WIDTH, bgViewH)];
        bgView.userInteractionEnabled = YES;
        //   bgView.backgroundColor = [UIColor redColor];
        _bgView = bgView;
        [self.view addSubview:bgView];
    }
    return _bgView;
}

- (UIImageView*)bgImageView
{
    if (!_bgImageView) {
        UIImageView* bg = [[UIImageView alloc] init];
        bg.userInteractionEnabled = YES;
        bg.backgroundColor = [UIColor whiteColor];
        bg.clipsToBounds = YES;
        bg.layer.cornerRadius = 10.0;
        _bgImageView = bg;
        [self.bgView addSubview:bg];
    }
    return _bgImageView;
}

- (UIImageView*)logoImageView
{
    if (!_logoImageView) {
        UIImageView* logo = [[UIImageView alloc] init];
        logo.image = [UIImage imageNamed:@"profile_logo"];
        logo.clipsToBounds = YES;
        logo.layer.cornerRadius = 10.0;
        _logoImageView = logo;
        [self.bgView addSubview:logo];
    }
    return _logoImageView;
}

- (UILabel*)userAccountLabel
{
    if (!_userAccountLabel) {
        UILabel* userLabel = [[UILabel alloc] init];
        NSString *userAccount = NSLocalizedString(@"userAccount", nil);
        userLabel.text = userAccount;
        userLabel.font = kLoginLalelFont;
        _userAccountLabel = userLabel;
        [self.bgImageView addSubview:userLabel];
    }
    return _userAccountLabel;
}

- (UILabel*)pwdAccountLabel
{
    if (!_pwdAccountLabel) {
        UILabel* pwdLabel = [[UILabel alloc] init];
        NSString *userPassWord = NSLocalizedString(@"userPassWord", nil);
        pwdLabel.text = userPassWord;
        pwdLabel.font = kLoginLalelFont;
        _pwdAccountLabel = pwdLabel;
        [self.bgImageView addSubview:pwdLabel];
    }
    return _pwdAccountLabel;
}

- (UITextField*)userAccountTextField
{
    if (!_userAccountTextField) {
        UITextField* userAccountTextField = [[UITextField alloc] init];
        NSString *userAccountPlaceholder = NSLocalizedString(@"userAccountPlaceholder", nil);
        userAccountTextField.placeholder = userAccountPlaceholder;
        [userAccountTextField setBorderStyle:UITextBorderStyleNone];
        [userAccountTextField setReturnKeyType:UIReturnKeyNext];
        userAccountTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [userAccountTextField setFont:[UIFont systemFontOfSize:18.0f]];
        userAccountTextField.delegate = self;
//        userAccountTextField.textColor = [UIColor customTextGrayBlackColor];
        userAccountTextField.keyboardType = UIKeyboardTypeNumberPad;
        userAccountTextField.font = kLoginTextFieldFont;
        userAccountTextField.text = [YWLoginTool loginUser].userAccount;
        _userAccountTextField = userAccountTextField;
        [self.bgImageView addSubview:userAccountTextField];
    }
    return _userAccountTextField;
}

- (UITextField*)pwdTextField
{
    if (!_pwdTextField) {
        UITextField* pwdTextField = [[UITextField alloc] init];
        NSString *userPassWordPlaceholder = NSLocalizedString(@"userPassWordPlaceholder", nil);
        pwdTextField.placeholder = userPassWordPlaceholder;
        [pwdTextField setBorderStyle:UITextBorderStyleNone];
        [pwdTextField setReturnKeyType:UIReturnKeyJoin];
        pwdTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [pwdTextField setFont:[UIFont systemFontOfSize:18.0f]];
        pwdTextField.delegate = self;
//        pwdTextField.textColor = [UIColor customTextGrayBlackColor];
        pwdTextField.secureTextEntry = YES;
        pwdTextField.keyboardType = UIKeyboardTypeASCIICapable;
        pwdTextField.font = kLoginTextFieldFont;
        _pwdTextField = pwdTextField;
        [self.bgImageView addSubview:pwdTextField];
    }
    return _pwdTextField;
}

- (UIButton*)loginBtn
{
    if (!_loginBtn) {
        UIButton* loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [loginBtn setBackgroundColor:[UIColor customBlueColor]];
        NSString *login = NSLocalizedString(@"login", nil);
        [loginBtn setTitle:login forState:UIControlStateNormal];
        loginBtn.clipsToBounds = YES;
        loginBtn.layer.cornerRadius = 5.0;
        [loginBtn addTarget:self action:@selector(loginClick:) forControlEvents:UIControlEventTouchUpInside];
        _loginBtn = loginBtn;
        [self.bgView addSubview:loginBtn];
    }
    return _loginBtn;
}

- (YWPopupOrganizationViewController*)popupOrganizationViewController
{
    if (!_popupOrganizationViewController) {
        YWPopupOrganizationViewController* popupOrganizationViewController = [[YWPopupOrganizationViewController alloc] init];
        popupOrganizationViewController.parentVC = self;
        popupOrganizationViewController.delegate = self;
        _popupOrganizationViewController = popupOrganizationViewController;
    }
    return _popupOrganizationViewController;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:self.view];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextLoginStart, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.view addSubview:hud];
    }
    return _HUD;
}

- (void)autoLayoutView
{
    //自动布局
    CGFloat leftPadding = 10;
    CGFloat topPadding = 15;
    CGSize logoSize = CGSizeMake(90, 90);
    CGSize labelSize = CGSizeMake(75, 30);
    CGFloat leftBgPadding = 15;

    [self.logoImageView mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.mas_equalTo(self.bgView.mas_top);
        make.centerX.mas_equalTo(self.bgView.mas_centerX);
        make.size.mas_equalTo(logoSize);
    }];

    [self.bgImageView mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.mas_equalTo(self.logoImageView.mas_bottom).offset(topPadding);
        make.left.mas_equalTo(self.bgView.mas_left).with.offset(leftBgPadding);
        make.right.mas_equalTo(self.bgView.mas_right).offset(-leftBgPadding);
        make.bottom.mas_equalTo(self.pwdAccountLabel.mas_bottom).offset(topPadding);
    }];

    [self.userAccountLabel mas_makeConstraints:^(MASConstraintMaker* make) {
        make.left.mas_equalTo(self.bgImageView.mas_left).with.offset(leftPadding);
        make.top.mas_equalTo(self.bgImageView.mas_top).with.offset(topPadding);
        make.size.mas_equalTo(labelSize);
    }];

    [self.userAccountTextField mas_makeConstraints:^(MASConstraintMaker* make) {
        make.centerY.mas_equalTo(self.userAccountLabel.mas_centerY);
        make.left.mas_equalTo(self.userAccountLabel.mas_right).with.offset(leftPadding);
        make.right.mas_equalTo(self.bgImageView.mas_right).with.offset(-leftPadding);
        make.height.mas_equalTo(self.userAccountLabel.mas_height);

    }];

    [self.pwdAccountLabel mas_makeConstraints:^(MASConstraintMaker* make) {
        make.left.mas_equalTo(self.userAccountLabel.mas_left);
        make.top.mas_equalTo(self.userAccountLabel.mas_bottom).with.offset(topPadding);
        make.size.mas_equalTo(labelSize);
    }];

    [self.pwdTextField mas_makeConstraints:^(MASConstraintMaker* make) {
        make.centerY.mas_equalTo(self.pwdAccountLabel.mas_centerY);
        make.left.mas_equalTo(self.pwdAccountLabel.mas_right).with.offset(leftPadding);
        make.right.mas_equalTo(self.bgImageView.mas_right).with.offset(-leftPadding);
        make.height.mas_equalTo(self.userAccountLabel.mas_height);

    }];

    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker* make) {
        make.height.mas_equalTo(kButtonH);
        make.left.mas_equalTo(self.bgImageView.mas_left);
        make.right.mas_equalTo(self.bgImageView.mas_right);
        make.top.mas_equalTo(self.bgImageView.mas_bottom).offset(topPadding);
    }];
}

#pragma mark - Action methods
- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event
{
    //点击 收起键盘
    [self.view endEditing:YES];
}

- (void)loginClick:(UIButton*)sender
{
    [self.view endEditing:YES];
    self.loginBtn.userInteractionEnabled = NO;

    [self.loginBtn shakeWithVelocity:@300
                     completionBlock:^{
                         [self startLogin];
                     }];
}

- (void)keyboardWillShow:(NSNotification*)notificontion
{
    NSDictionary* info = [notificontion userInfo];
    NSValue* value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [self moveUpBgViewWithKeyboardHeight:keyboardSize.height animationDuration:duration];
}

- (void)keyboardWillHide:(NSNotification*)notificontion
{
    NSDictionary* info = [notificontion userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [self moveDownBgViewWithDuration:duration];
}

#pragma mark - Common methods
//- (void)registerForKeyboardNotifications
//{
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
//}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/**
 *  挡住登录按钮时，向上移动
 *
 *  @param height 弹出键盘的高度
 *  @param duration 动画时间
 */
- (void)moveUpBgViewWithKeyboardHeight:(CGFloat)height animationDuration:(CGFloat)duration
{
    CGFloat bgViewMaxY = CGRectGetMaxY(self.bgView.frame);
    if (SCREEN_HEIGHT - bgViewMaxY >= height) {
        return;
    }

    [UIView beginAnimations:@"KeyboardMoveUpAnimaitons" context:nil];
    self.bgView.y = SCREEN_HEIGHT - self.bgView.height - height;

    [UIView setAnimationDuration:duration];
    [UIView commitAnimations];
}

/**
 *  键盘弹下，还原界面
 *
 *  @param duration 动画时间
 */
- (void)moveDownBgViewWithDuration:(CGFloat)duration
{
    if (originalBgViewY == self.bgView.y) {
        return;
    }
    [UIView beginAnimations:@"KeyboardMoveDownAnimaitons" context:nil];
    NSTimeInterval animationDuration = duration;

    self.bgView.y = originalBgViewY;

    [UIView setAnimationDuration:animationDuration];
    [UIView commitAnimations];
}

- (void)startLogin
{
    if ([self checkInput]) {
        if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
            self.HUD.labelText = NSLocalizedString(kTextLoginStart, nil);
            [self.HUD show:YES];
            [self preLoginRequest];
        }
        else {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
    }
    else {
        [self.HUD hide:YES];
    }
}

/**
 *  检验输入内容是否为空，是否合法
 *
 *  @return 检验结果
 */
- (BOOL)checkInput
{
    if (![self checkUserAccount]) {
        return NO;
    }

    if (![self checkPwd]) {
        return NO;
    }
    return YES;
}

- (BOOL)checkUserAccount
{
    NSString* userAccount = [_userAccountTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (userAccount.length == 0) {
        [self contentIsNullHandleWithTextField:_userAccountTextField];
        return NO;
    }
    return YES;
}

- (BOOL)checkPwd
{
    if (_pwdTextField.text.length == 0) {
        [self contentIsNullHandleWithTextField:_pwdTextField];
        return NO;
    }
    return YES;
}

- (void)preLoginRequest
{
    NSString *userAccount = [_userAccountTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *passWord = _pwdTextField.text;
    [YWLoginTool preLoginRequestWithUserName:userAccount passWord:passWord isLogin:YES completeBlock:^(NSArray* organizations) {
        if (organizations.count == 1) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                YWOrganization* organization = organizations[0];
                [self loginRequestWithOrganizationNo:organization.organizationNo simpleName:organization.simpleName];
            });
        }else if (organizations.count > 1) {
            [self.HUD hide:YES];
            self.popupOrganizationViewController.organizations = organizations;
            [self presentPopupViewController:self.popupOrganizationViewController animationType:MJPopupViewAnimationSlideBottomBottom];
        }else{
            [self.HUD hide:YES];
        }
    }];
}

- (void)loginRequestWithOrganizationNo:(NSString*)companyAccount simpleName:(NSString*)simpleName{
    NSString* userAccount = [_userAccountTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *passWord = _pwdTextField.text;
    [YWLoginTool loginRequestWithOrganizationNo:companyAccount simpleName:simpleName userName:userAccount passWord:passWord isLogin:YES completeBlock:^(NSInteger statusCode) {
        if (statusCode == 200) {
            //下载json数据
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self downloadMetaDatas];
            });
        }else{
            [self.HUD hide:YES];
        }
    }];
}

- (void)downloadMetaDatas
{
    if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
        //  WMNetworkType type = [WMHttpTool shareHttpTool].networkType;
        self.HUD.labelText = NSLocalizedString(kTextDownloadMetaData, nil);
        [self.HUD show:YES];
        [[YWDownloadMetaDataManager shareManager] serialDownloadDatasWithComplete:^(BOOL error) {
            [self.HUD hide:YES];
            if (error) {
                //                if (![[YWResourceManager shareManager] downloadedStaticData]) {
                //  [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextDownloadMetaDataFail, nil)];
                //  return;
                //                }
            }else {
                //[[YWResourceManager shareManager] saveDownloadedStaticData];
            }
            UIWindow* window = [UIApplication sharedApplication].keyWindow;
            [window switchRootViewController];
            //各个模块的未读数和总数
            [[YWEwinManager shareManager] selectIsExistNewMissionsUnReadCount];
        }];
    }
    else {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
    }
}

/**
 *  输入框内容为空时处理
 *
 *  @param textField 输入框
 */
- (void)contentIsNullHandleWithTextField:(UITextField*)textField
{
    [self alertContentIsNullWithBtnBlock:^{
        [textField becomeFirstResponder];
    }
        dismissBlock:^{
            [textField becomeFirstResponder];
        }];
}

/**
 *  输入框内容为空时显示提示框
 *
 *  @param btnBlock     点击按钮后调用的代码块
 *  @param dismissBlock 点击关闭后调用的代码块
 */
- (void)alertContentIsNullWithBtnBlock:(dispatch_block_t)btnBlock dismissBlock:(dispatch_block_t)dismissBlock
{
    NSString *title = NSLocalizedString(@"tips", nil);
    NSString *ok = NSLocalizedString(@"ok", nil);
    NSString *message = NSLocalizedString(kTextLoginInputEmpty, nil);
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:ok style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        if (btnBlock) {
            btnBlock();
        }
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - YWPopupSelectOrganizationDelegate
- (void)selectedOrganization:(YWOrganization*)organization
{
    [self.HUD show:YES];
    [self loginRequestWithOrganizationNo:organization.organizationNo simpleName:organization.simpleName];
}

#pragma mark - UITextFieldDelegate methods
- (BOOL)textFieldShouldReturn:(UITextField*)textField
{
    if (textField == _userAccountTextField) {
        [_pwdTextField becomeFirstResponder];
    }
    else {
        [_pwdTextField resignFirstResponder];
        [self startLogin];
    }
    return YES;
}
@end
